<template>
  <el-dialog
    :title="title"
    :visible.sync="Visible"
    size="tiny"
  >
    <el-form :model="ruleForm" ref="ruleForm" label-position="right"  label-width="100px" class="small-space">
      <el-row v-loading.body="listLoading">
        <el-col :span="18" :offset="2">
          <el-form-item label="卡种" prop="title">
            <el-select
              v-model="ruleForm.cards_type_id"
              filterable
              placeholder="请选卡种">
              <el-option
                v-for="item in cardTypeData.data"
                :key="item.id"
                :label="`${item.title}`"
                :value="item.id">
              </el-option>
            </el-select>
            <div class="el-form-item__error" v-if="errors.cards_type_id">{{errors.cards_type_id ? errors.cards_type_id[0] : ''}}</div>
          </el-form-item>

          <el-form-item  label="有效期范围">
            <el-date-picker
              v-model="ruleForm.dateRange"
              type="daterange"
              align="right"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="pickerChange"
            >
            </el-date-picker>
            <div class="el-form-item__error" v-if="errors.start_date">{{errors.start_date ? errors.start_date[0] : ''}}</div>
            <div class="el-form-item__error" v-if="errors.end_start">{{errors.end_start ? errors.end_start[0] : ''}}</div>
          </el-form-item>

          <el-form-item
            v-for="(condition, index) in ruleForm.conditions"
            :label="`赠卡条件 ${index+1}`"
            :key="Date.now()"
            :prop="'conditions.' + index + '.need_num'"
          >
            <el-input style="width: 100px" v-model="condition.need_num" placeholder="赠卡人数"></el-input>
            <el-select
              v-model="condition.cards_type_id"
              filterable
              placeholder="赠卡卡种">
              <el-option
                v-for="(item, index) in cardTypeData.data"
                :key="item.id"
                :label="`${item.title}`"
                :value="item.id">
              </el-option>
            </el-select>
            <el-button @click.prevent="removeCondition(condition)">删除</el-button>
            <div class="el-form-item__error"
                 v-if="errors[`conditions.${index}.cards_type_id`] || errors[`conditions.${index}.need_num`]">
              {{`${errors[`conditions.${index}.cards_type_id`][0] ? errors[`conditions.${index}.cards_type_id`][0] : ''}
              ${errors[`conditions.${index}.need_num`][0] ? errors[`conditions.${index}.need_num`][0] : ''}`}}
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="addCondition">新增赠卡条件</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import _ from 'lodash'
import { GetAllCardType, Create, Update, Show } from '../../api/giftCards'

export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String
    },
    editId: {}
  },
  data() {
    return {
      cardTypeData: [],
      errors: {},
      listLoading: false,
      Visible: this.dialogVisible,
      loadTable: false, // 这是关闭对话框之后是否重新读列表的状态
      ruleForm: {
        cards_type_id: null,
        start_date: '',
        end_date: '',
        dateRange: [],
        conditions: [
          {
            cards_type_id: '',
            need_num: ''
          }
        ]
      }
    }
  },
  watch: {
    async dialogVisible() {
      if (this.dialogVisible) {
        this.loadTable = false
        this.Visible = this.dialogVisible
        this.resetForm('ruleForm')

        this.cardTypeData = await GetAllCardType()

        //          ↓ 打开的时候
        if (this.title === '编辑') {
          this.listLoading = true
          const res = await Show(this.editId)
          this.ruleForm = res.data
          this.ruleForm.conditions = this.ruleForm.conditions.data
          this.ruleForm.dateRange = [res.data.start_date, res.data.end_date]
          this.listLoading = false
        }
      }
    },
    Visible() {
      this.$emit('closeDialog', this.loadTable)
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.listLoading = true
          const data = _.pick(this.ruleForm, ['cards_type_id', 'start_date', 'end_date', 'conditions'])
          if (this.title === '编辑') {
            Update(this.editId, data).then(res => {
              this.listLoading = false
              this.$message({ message: '保存成功', type: 'success' })
              this.resetForm('ruleForm') // 清空表单
              this.loadTable = true
              this.Visible = false // 关闭对话框
            }).catch((error) => {
              const { response } = error
              this.errors = response.data.errors
              this.listLoading = false
            })
          } else {
            Create(data).then(res => {
              this.listLoading = false
              this.$message({ message: '保存成功', type: 'success' })
              this.resetForm('ruleForm')
              this.loadTable = true
              this.Visible = false
            }).catch((error) => {
              const { response } = error
              this.errors = response.data.errors
              this.listLoading = false
            })
          }
        }
      })
    },
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields()
      })
    },
    pickerChange(date) {
      this.ruleForm.start_date = date[0]
      this.ruleForm.end_date = date[1]
    },
    addCondition() {
      this.ruleForm.conditions.push({
        need_num: '',
        cards_type_id: ''
      })
    },
    removeCondition(item) {
      const index = this.ruleForm.conditions.indexOf(item)
      if (index !== -1) {
        this.ruleForm.conditions.splice(index, 1)
      }
    }
  }
}
</script>
